package cn.buk.tms.eotms.service;

import cn.buk.common.sc.CommonSearchCriteria;
import cn.buk.common.util.DateUtil;
import cn.buk.tms.eotms.dao.PnrDao;
import cn.buk.tms.eotms.dao.UserDao;
import cn.buk.tms.eotms.dto.TicketSaleDto;
import cn.buk.tms.eotms.entity.DetrInfo;
import cn.buk.tms.eotms.entity.TicketSale;
import cn.buk.tms.eotms.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class FlightServiceImpl extends BaseAbstractService implements FlightService {

  @Autowired
  private PnrDao pnrDao;

  @Autowired
  private UserDao userDao;

  @Override
  public List<TicketSaleDto> searchTprs(final int userId, Date beginDate, Date endDate, String etermUsername, int deviceId, String ticketNo, CommonSearchCriteria sc) {
    if (beginDate != null && endDate != null && DateUtil.getDaySpan(endDate, beginDate) >= 40) {
      return new ArrayList<>();
    }

    final int ownerId = getOwnerIdByUserId(userId);

    //根据用户的etermUsername进行查询
    User user = userDao.getUserById(userId);
    String[] etermUserNames = user.getEtermUsername().length() == 0 ? user.getEmpname().split(",") : user.getEtermUsername().split(",");
    if (etermUserNames == null || etermUserNames.length == 0) {
      return new ArrayList<>();
    }

    List<TicketSale> results = pnrDao.searchTprs(ownerId, beginDate, endDate, deviceId, ticketNo, sc, etermUserNames);


    List<TicketSaleDto> dtos = new ArrayList<>();

    for (TicketSale info : results) {
      TicketSaleDto dto = new TicketSaleDto();
      BeanUtils.copyProperties(info, dto);

      dtos.add(dto);
    }

    return dtos;
  }

  @Override
  public List<DetrInfo> searchDetrs(final int userId, CommonSearchCriteria sc) {
    final int ownerId = getOwnerIdByUserId(userId);

    //根据用户的etermUsername进行查询
    User user = userDao.getUserById(userId);
    String[] etermUserNames = user.getEtermUsername().length() == 0 ? user.getEmpname().split(",") : user.getEtermUsername().split(",");
    if (etermUserNames == null || etermUserNames.length == 0) {
      return new ArrayList<>();
    }

    return pnrDao.searchDetrs(ownerId, sc, etermUserNames);
  }
}
